package com.weihe.toolkit.regex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.lang.StringUtils;

public class RegexToolkit {
	
	/**
	 * 
	 * @param regex Regular expression
	 * @param content to match string
	 * @param matchGroup
	 * @return matched string list
	 * eg:"Number:\s*(.*)\s*Signature"  matchGroup=0 whole match string,matchGroup=1 (.*) match string,
	 */
	public static List<String> getMatchString(String regex,String content,int matchGroup){
		if(StringUtils.isNotBlank(regex)&&StringUtils.isNotBlank(content)){
			Pattern pattern = Pattern.compile(regex);
			 Matcher matcher = pattern.matcher(content);
			 List<String> list = new ArrayList<String>();
			 while (matcher.find()) {
				 list.add(matcher.group(matchGroup));
			 }
			 return list;
		}else{
			return null;
		}
	}
	
	public static List<String> replaceString(String regex,String replace,String content){
		if(StringUtils.isNotBlank(regex)&&StringUtils.isNotBlank(content)){
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(content);
			List<String> list = new ArrayList<String>();
			while (matcher.find()) {
				list.add(matcher.replaceAll(replace));
			}
			return list;
		}else{
			return null;
		}
	}
	
	/**
	 * 
	 * @param str
	 * @param regex  "[\\w|-| ]"
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String StringFilter(String str, String regex) throws PatternSyntaxException {
		if(StringUtils.isNotBlank(str) && StringUtils.isNotBlank(regex)){
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(str);
			StringBuilder sb = new StringBuilder();
			while (m.find()) {
				sb.append(m.group(0));
			}
			return sb.toString();
		}
		return str;
	}
	
}
